import ls from 'store2'
import { checkTerminal } from '~/common/common'
export default ({ app }) => {
  app.router.beforeEach((to, from, next) => {
    if (to.query.sxmall_return_url) {
      let sxuri = decodeURIComponent(to.query.sxmall_return_url)
      if (/\?/.test(sxuri)) {
        sxuri = sxuri + '&'
      } else {
        sxuri = sxuri + '?'
      }
      app.store.commit('changeParam', sxuri)
      if (ls.get('tokensyxk') && ls.get('wxopen_id') && ls.get('userVoId')) {
        let urls = sxuri + 'sx_uid=' + ls.get('userVoId') + '&sx_token=' + ls.get('tokensyxk') + '&trace_id=' + sessionStorage.getItem('trace_id') + '&open_id=' + ls.get('wxopen_id')
        window.location.replace(urls)
      } else {
        app.router.replace({
          path: '../login/msgLogin',
          query: {
            returnMall: sxuri,
          },
        })
      }
    }
    if (to.query.mini_token || to.query.from === 'smallProgram') {
      sessionStorage.setItem('fromplat', 'program')
      let yxkData = {
        userId: to.query.userId,
        userVoId: to.query.userVoId,
      }
      ls.set('yxkData', yxkData)
      ls.set('userType', to.query.userType)
      ls.set('userVoId', to.query.userVoId)
      ls.set('tokensyxk', to.query.mini_token)
      ls.set('userArea', decodeURI(to.query.userArea))
    }
    if (checkTerminal() === 'ios') {
      let iOSInfos = window.iOSInfo
      if (Object.keys(iOSInfos).length > 0) {
        ls.set('yxkData', iOSInfos)
        ls.set('userType', iOSInfos.userType)
        ls.set('tokensyxk', iOSInfos.tokens)
        ls.set('userArea', iOSInfos.userArea)
      }
    }
    if (checkTerminal() === 'android') {
      let data = window.ZMParentsJsToAndroid.getZyMsg()
      let androidData = JSON.parse(data)
      if (androidData.userType) {
        ls.set('yxkData', androidData)
        ls.set('userType', androidData.userType)
        ls.set('tokensyxk', androidData.tokens)
        ls.set('userArea', androidData.userArea)
      }
    }
    next()
  })
}
